import { ref, onMounted, computed } from "vue";

const DB_NAME = "MyDatabase";
let MY_STORE_List = ref([]);
let CHECK_STORE_List = ref([]);
const STORE_NAMES = {
  MY_STORE: "MyStore",
  CHECK_STORE: "CheckStore",
};
let db = null;
// 初始化数据库
// 初始化数据库
export const initDB = () => {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open(DB_NAME, 3); // 版本号升级

    request.onupgradeneeded = (event) => {
      const db = event.target.result;

      // 创建或升级MyStore表
      if (!db.objectStoreNames.contains(STORE_NAMES.MY_STORE)) {
        const store = db.createObjectStore(STORE_NAMES.MY_STORE, {
          keyPath: "id",
          autoIncrement: true,
        });
        store.createIndex("index", "index", { unique: false });
        store.createIndex("name", "name", { unique: false });
        store.createIndex("path", "path", { unique: false });
        store.createIndex("bgPath", "bgPath", { unique: false });
        store.createIndex("containerStyle", "containerStyle", {
          unique: false,
        });
        store.createIndex("chartStyle", "chartStyle", { unique: false });
        store.createIndex("position", "position", { unique: false });
      }

      // 创建或升级CheckStore表
      if (!db.objectStoreNames.contains(STORE_NAMES.CHECK_STORE)) {
        const store = db.createObjectStore(STORE_NAMES.CHECK_STORE, {
          keyPath: "id",
          autoIncrement: true,
        });
        store.createIndex("index", "index", { unique: false });
        store.createIndex("name", "name", { unique: false });
        store.createIndex("path", "path", { unique: false });
        store.createIndex("bgPath", "bgPath", { unique: false });
        store.createIndex("containerStyle", "containerStyle", {
          unique: false,
        });
        store.createIndex("chartStyle", "chartStyle", { unique: false });
        store.createIndex("position", "position", { unique: false });
      }
    };

    request.onsuccess = (event) => {
      db = event.target.result;
      initializeStores();
      resolve(db);
    };

    request.onerror = (event) => {
      console.error("数据库打开失败", event);
      reject("数据库打开失败");
    };
  });
};

// 初始化表数据
const initializeStores = async () => {
  await initializeStore(STORE_NAMES.MY_STORE, [
    {
      index: 1,
      name: "view1",
      path: "./visualization/view1.vue",
      bgPath: "./visualization/bg/view1_a.vue",
      containerStyle:
        "height:300px;width:30%;overflow:hidden;position:absolute;top:80px;left:0;z-index:10;",
      chartStyle: "width: 90%; height: 80%;",
      position: "left",
    },
    {
      index: 3,
      name: "view3",
      path: "./visualization/view3.vue",
      bgPath: "./visualization/bg/view3_a.vue",
      containerStyle:
        "height:300px;width:30%;overflow:hidden;overflow:hidden;position:absolute;top:380px;left:0;z-index:10;",
      chartStyle: "width: 80%; height: 55%;",
      position: "left",
    },
    {
      index: 3,
      name: "left3",
      path: "./visualization/left3.vue",
      bgPath: "./visualization/bg/left3.vue",
      containerStyle: "height:400px;width:30%;position:absolute;top:680px;left:0;z-index:10;",
      chartStyle: "width: 80%; height: 80%;display:none;",
      position: "left",
    },
    {
      index: 1,
      name: "center1",
      path: "./visualization/center1.vue",
      bgPath: "./visualization/bg/center1.vue",
      containerStyle: "height:100px;width:40%;overflow:hidden;position:absolute;top:10px;left:30%;z-index:10;",
      chartStyle: "width: 80%; height: 80%;display:none;",
      position: "center",
    },
    {
      index: 2,
      name: "view2",
      path: "./visualization/view2.vue",
      bgPath: "./visualization/bg/view2_a.vue",
      containerStyle: "height:580px;width:40%;overflow:hidden;position:absolute;top:90px;left:30%;z-index:10;",
      chartStyle: "width: 80%; height: 80%;",
      position: "center",
    },
    {
      index: 3,
      name: "center3",
      path: "./visualization/left3.vue",
      bgPath: "./visualization/bg/left3.vue",
      containerStyle: "height:400px;width:40%;position:absolute;top:680px;left:30%;z-index:10;",
      chartStyle: "width: 80%; height: 80%;display:none;",
      position: "center",
    },
    {
      index: 1,
      name: "right1",
      path: "./visualization/right1.vue",
      bgPath: "./visualization/bg/right1.vue",
      containerStyle: "height:400px;width:30%;position:absolute;top:80px;left:70%;z-index:10;",
      chartStyle: "width: 80%; height: 80%;display:none;",
      position: "center",
    },
    {
      index: 3,
      name: "right2",
      path: "./visualization/left3.vue",
      bgPath: "./visualization/bg/right2.vue",
      containerStyle: "height:300px;width:30%;position:absolute;top:380px;left:70%;z-index:10;overflow:hidden;",
      chartStyle: "width: 80%; height: 70%;display:none;",
      position: "left",
    },
    
    {
      index: 3,
      name: "right2",
      path: "./visualization/left3.vue",
      bgPath: "./visualization/bg/right2.vue",
      containerStyle: "height:300px;width:30%;position:absolute;top:380px;left:70%;z-index:10;overflow:hidden;",
      chartStyle: "width: 80%; height: 70%;display:none;",
      position: "left",
    },
    {
      index: 3,
      name: "right3",
      path: "./visualization/right3.vue",
      bgPath: "./visualization/bg/right3.vue",
      containerStyle: "height:300px;width:30%;position:absolute;top:680px;left:70%;z-index:10;",
      chartStyle: "width: 92%; height: 90%;margin-left:15px;margin-top:20px;",
      position: "right",
    },
  ]);

  await initializeStore(STORE_NAMES.CHECK_STORE, [
    {
      index: 1,
      name: "view1",
      path: "./view1.vue",
      bgPath: "./bg/view1.vue",
      containerStyle: "height:330px;width:calc(50% - 30px)",
      chartStyle: "width: 100%; height: 100%;margin-left:30px;",
      position: "left",
    },
    {
      index: 2,
      name: "view2",
      path: "./view2.vue",
      bgPath: "./bg/view2.vue",
      containerStyle: "height:330px;width:calc(50% - 30px)",
      chartStyle: "width: 80%; height: 80%;margin-left:80px;",
      position: "left",
    },
    {
      index: 3,
      name: "view3",
      path: "./view3.vue",
      bgPath: "./bg/view3.vue",
      containerStyle: "height:330px;width:calc(50% - 30px)",
      chartStyle: "width: 80%; height:70%;",
      position: "left",
    },
    {
      index: 4,
      name: "view4",
      path: "./view4.vue",
      bgPath: "./bg/view4.vue",
      containerStyle: "height:330px;width:calc(50% - 30px)",
      chartStyle: "width: 80%; height: 80%;margin-left:80px;",
      position: "left",
    },
    {
      index: 5,
      name: "center1",
      path: "./center1.vue",
      bgPath: "./bg/center1.vue",
      containerStyle: "height:330px;width:calc(50% - 30px)",
      chartStyle: "width: 80%; height: 80%;display:none;",
      position: "center",
    },
    {
      index: 6,
      name: "left3",
      path: "./left3.vue",
      bgPath: "./bg/left3.vue",
      containerStyle: "height:330px;width:calc(50% - 30px)",
      chartStyle: "width: 80%; height: 80%;display:none;",
      position: "center",
    },    
    {
      index: 7,
      name: "right2",
      path: "./left3.vue",
      bgPath: "./bg/right2.vue",
      containerStyle: "height:330px;width:calc(50% - 30px);",
      chartStyle: "width: 80%; height: 80%;display:none;",
      position: "right",
    },    
    {
      index: 8,
      name: "right1",
      path: "./right1.vue",
      bgPath: "./bg/right1.vue",
      containerStyle: "height:330px;width:calc(50% - 30px);",
      chartStyle: "width: 80%; height: 80%;",
      position: "right",
    },
  ]);
};

// 初始化单个表
const initializeStore = (storeName, initialData) => {
  return new Promise((resolve) => {
    const transaction = db.transaction(storeName, "readonly");
    const store = transaction.objectStore(storeName);
    const countRequest = store.count();

    countRequest.onsuccess = () => {
      if (countRequest.result === 0) {
        // 表为空，添加初始数据
        const writeTransaction = db.transaction(storeName, "readwrite");
        const writeStore = writeTransaction.objectStore(storeName);

        initialData.forEach((item) => {
          writeStore.add(item);
        });

        writeTransaction.oncomplete = () => {
          // refreshItems(storeName, itemsRef);
          resolve();
        };
      } else {
        // 表已有数据，直接加载
        // refreshItems(storeName, itemsRef);
        resolve();
      }
    };
  });
};

export const refreshItems = (storeName, callback) => {
  const request = indexedDB.open(DB_NAME, 3);

  request.onsuccess = (event) => {
    const db = event.target.result;
    const transaction = db.transaction(storeName, "readonly");
    const store = transaction.objectStore(storeName);
    const getAllRequest = store.getAll();

    getAllRequest.onsuccess = () => {
      callback(getAllRequest.result);
    };

    getAllRequest.onerror = () => {
      console.error(`加载${storeName}数据失败`);
      callback([]);
    };
  };

  request.onerror = (event) => {
    console.error("数据库打开失败:", event);
    callback([]);
  };
};

const add_my_store = (item: any) => {
  const writeTransaction = db.transaction(STORE_NAMES.MY_STORE, "readwrite");
  const writeStore = writeTransaction.objectStore(STORE_NAMES.MY_STORE);
  writeStore.add(item);
  writeTransaction.oncomplete = () => {
    console.log("数据插入成功！");
  };
};

//分页方法调用
export const getItemsByPage = (
  storeName: string,
  page: number,
  pageSize: number
): Promise<any[]> => {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open(DB_NAME, 3);

    request.onsuccess = (event) => {
      const db = event.target.result;
      const transaction = db.transaction(storeName, "readonly");
      const store = transaction.objectStore(storeName);
      const countRequest = store.count();

      countRequest.onsuccess = () => {
        const total = countRequest.result;
        const totalPages = Math.ceil(total / pageSize);

        if (page < 1 || page > totalPages) {
          resolve([]);
          return;
        }

        const offset = (page - 1) * pageSize;
        // 使用游标来实现正确的分页
        const cursorRequest = store.openCursor();
        let results = [];
        let advanced = false;
        let counter = 0;

        cursorRequest.onsuccess = (e) => {
          const cursor = e.target.result;
          if (!cursor) {
            resolve({
              data: results,
              total,
              page,
              pageSize,
              totalPages,
            });
            return;
          }

          if (!advanced && offset > 0) {
            cursor.advance(offset);
            advanced = true;
            return;
          }

          if (counter < pageSize) {
            results.push(cursor.value);
            counter++;
            cursor.continue();
          } else {
            resolve({
              data: results,
              total,
              page,
              pageSize,
              totalPages,
            });
          }
        };

        cursorRequest.onerror = () => {
          console.error(`获取${storeName}分页数据失败`);
          reject([]);
        };
      };

      countRequest.onerror = () => {
        console.error(`获取${storeName}总数失败`);
        reject([]);
      };
    };

    request.onerror = (event) => {
      console.error("数据库打开失败:", event);
      reject([]);
    };
  });
};
/*
分页方法使用示例
getItemsByPage(STORE_NAMES.MY_STORE, 1, 10)
  .then(result => {
    console.log('分页数据:', result);
  })
  .catch(error => {
    console.error('获取分页数据出错:', error);
  });
 */
